package org.itboys.framework.rpc;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.SecureRandom;

/**
 * 基于 和手机端通信 servlet api相关重写
 * @author ChenJh
 *
 */
public interface RpcServletHolder {

	public static final String SESSION_KEY = "sk";

	/**
	 * 重写session逻辑 将对象基于redis存session 避免在地址栏传会员ID之类比较挫的设计
	 * @param request
	 * @param sessionKey
	 * @param value
	 * @return
	 */
	public <T> boolean addToSession(HttpServletRequest request, HttpServletResponse response, String sessionKey, T value) ;

	/**
	 * 从session 中获取
	 * @param request
	 * @param sessionKey
	 * @param <T>
	 * @return
	 */
	public Object getValueFromSession(HttpServletRequest request, HttpServletResponse response, String sessionKey);

	public default String getSessionId(HttpServletRequest request) {
		//TODO 同一个IP 频繁伪造请求头的情况下 要做防范 不然到时候乔工攻击
		String sessionId = request.getHeader(SESSION_KEY);
		return StringUtils.isBlank(sessionId) ? genSessionKey() : sessionId;
	}

	public default String genSessionKey() {
		SecureRandom random = new SecureRandom();
		byte bytes[] = new byte[20];
		random.nextBytes(bytes);
		return DigestUtils.sha1Hex(bytes);
	}
}
